<?php if (!defined("BASEPATH")) exit("No direct script access allowed"); ?>

<script type="text/javascript">
	Ext.onReady(function() {

		var winNewsletter; // edit ablak
		var newsletterForm; // form panel

		var store = new Ext.data.JsonStore({
			totalProperty: 'total', 
			root: 'results', 
			sortInfo: {field: 'nltSubject', direction: 'ASC'},
			remoteSort: true,
			proxy : new Ext.data.HttpProxy({
				url: '<?=site_url()?>admin/get_newsletter',
				method: 'GET'
			}),
			fields: [
				{name: 'nltId'},
				{name: 'nltSubject'},
				{name: 'nltText'},
				{name: 'nltSent'}
			]
		});

		var grid = new Ext.grid.GridPanel({
			store: store,
			id: 'newsletterGrid',
			viewConfig:{
				emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>'
			},
			columns: [
				{header: '<?=$this->db->escape_str($this->lang->line("SUBJECT"))?>', width: 150, sortable: true, dataIndex: 'nltSubject'},
				{id:'nltText', header: '<?=$this->db->escape_str($this->lang->line("TEXT"))?>', width: 350, sortable: false, dataIndex: 'nltText', renderer: function (val) { 
					stripVal = val.replace(/<[^>]*>/g, '');
					if(stripVal.length > 400) {
						return stripVal.substr(0,400) + '...';
					} else {
						return val;
					}
				}},
				{header: '<?=$this->db->escape_str($this->lang->line("SENT"))?>', width: 50, sortable: true, align: 'center', dataIndex: 'nltSent', renderer: function(val) { return '<span style="color:' + ((val == 'I')?('green'):('red')) + ';">' + ((val == 'I')?('<?=$this->db->escape_str($this->lang->line("YES"))?>'):('<?=$this->db->escape_str($this->lang->line("NO"))?>')) + '</span>'; }}
			],
			stripeRows: true,
			autoExpandColumn: 'nltText',
			autoHeight: true,
			autoWidth: true,
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),

			listeners: {

				rowdblclick: function(grid, rowIndex, event) {
					if(rowIndex != 'new') {
						var record = grid.getStore().getAt(rowIndex);
					} else {
						var record = new Object();
						record.data = new Object();
					}

					if(winNewsletter) {
						winNewsletter.close();
					}
					winNewsletter = new Ext.Window({
						iconCls: (rowIndex == 'new')?('application_form_add'):('application_form_edit'),
						layout:'',
						bodyStyle: 'background-color:white',
						autoScroll: true,
						maximized: false,
						modal: true,
						width:700,
						floating: true,
						minWidth: 700,
						height:500,
						minHeight: 500,
						closeAction:'close',
						maximizable: false,
						title: (rowIndex == 'new')?('<?=$this->db->escape_str($this->lang->line("ADD_NEW_NEWSLETTER"))?>'):('<?=$this->db->escape_str($this->lang->line("HIRLEVEL_SZERKESZTESE"))?> - ' + record.data.nltSubject),

						listeners: {
							close: function() {
								store.reload(store.lastOptions);
							}
						},

						items:[{

									border: false,

									items: newsletterForm = new Ext.FormPanel({
										padding: 10,
										labelAlign: 'right',
										labelWidth: 100,
										autoHeight: true,
										autoWidth: true,
										border: false,
										defaultType: 'textfield',
										waitMsgTarget: true,
										items: [{
												hidden: true,
												inputType: 'hidden',
												name: 'nlt_id',
												value: record.data.nltId
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("TITLE_OF_NEWSLETTER"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													xtype: 'textfield',
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("TITLE_OF_NEWSLETTER"))?>',
													name: 'nlt_subject',
													value: record.data.nltSubject,
													maxLength: 255,
													maxLengthText: '<?=$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))?>',
													allowBlank: false,
													blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
													anchor:'100%'
												}]
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("TEXT"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													xtype: 'textfield',
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("TEXT"))?>',
													xtype: 'htmleditor',
													enableColors: true,
													enableLinks: true,
													enableFont: true,
													enableSourceEdit: true,
													name: 'nlt_text',
													anchor:'100%',
													height: 300,
													value: record.data.nltText,
													listeners: {
														render: function(editor) {
															editor.getToolbar().insertButton(editor.getToolbar().items.length, {
																iconCls: 'upload-icon',
																handler: function(b,e) {
																	Ext.Msg.prompt('Insert Image', 'Image URL', function(btn, txt) {
																		if (btn == 'ok') {
																			editor.relayCmd('insertimage', txt);
																		}
																	});                                            
																}
															});
														}
													}
												}]
											}
										]

									})

								}

							],

							bbar: {
								items: [{
									text: '<?=$this->db->escape_str($this->lang->line("SAVE"))?>',
									handler: save,
									icon: '<?=MEDIA?>icon/disk.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
									handler: close,
									icon: '<?=MEDIA?>icon/cancel.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("RESET"))?>',
									handler: function() {
										newsletterForm.getForm().reset();
									}
								}],
								buttonAlign : 'right'
							}

					});
					winNewsletter.show(this);

				}
			},
			border: false,

			frame:false,

			tbar: {
				items: [{
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_NEWSLETTER"))?>',
						handler: function(){
							grid.fireEvent('rowdblclick', grid, 'new', new Object());
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("EDITING_NEWSLETTER"))?>',
						ref: '../removeBtn',
						disabled: true,
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_NEWSLETTERS"))?> (' + grid.getSelectionModel().getSelections()[0].data.nltSubject + ')?' , removeNewsletter);
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/email_go.png',
						text: '<?=$this->db->escape_str($this->lang->line("SENDING_NEWSLETTER"))?>',
						ref: '../sendBtn',
						disabled: true,
						handler: function(){

							var record = Ext.getCmp('newsletterGrid').getSelectionModel().getSelected();

							if(winNewsletter) {
								winNewsletter.close();
							}
							winNewsletter = new Ext.Window({
								iconCls: 'application_go',
								layout:'',
								bodyStyle: 'background-color:white',
								autoScroll: true,
								modal: true,
								width:500,
								floating: true,
								minWidth: 500,
								height:350,
								minHeight: 350,
								closeAction:'close',
								maximizable: false,
								title: '<?=$this->db->escape_str($this->lang->line("SENDING_NEWSLETTER"))?> - ' + record.data.nltSubject,

								listeners: {
									close: function() {
										store.reload(store.lastOptions);
									}
								},

								items:[{

											border: false,

											items: [
												new Ext.Panel({ 
													layout: 'fit', 
													border: true,
													html: '<?=$this->db->escape_str($this->lang->line("MORE_E-MAIL_ADDRES_PLEASE_SEPARATE_WITH"))?>',
													padding: 5,
													style: {margin: '5px'}
												}),
												newsletterForm = new Ext.FormPanel({
													padding: 10,
													labelAlign: 'right',
													labelWidth: 50,
													autoHeight: true,
													autoWidth: true,
													border: false,
													defaultType: 'textfield',
													waitMsgTarget: true,
													items: [{
															hidden: true,
															inputType: 'hidden',
															name: 'nlt_id',
															value: record.data.nltId
														}, {
															xtype:'fieldset',
															title: '<?=$this->db->escape_str($this->lang->line("LIST_OF_ADDRESS"))?>',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [
																new Ext.form.TextArea({
																	fieldLabel: '<?=$this->db->escape_str($this->lang->line("LIST_OF_ADDRESS"))?>',
																	grow: true,
																	id: 'frmNltAddressList',
																	height: 150,
																	name: 'nlt_address_list',
																	allowBlank: false,
																	blankText: '<?=$this->db->escape_str($this->lang->line("A mező megadása kötelező!"))?>',
																	anchor:'100%'
																})
															]
														}
													]

												})
											]

										}

									],

									bbar: {
										items: [{
											text: '<?=$this->db->escape_str($this->lang->line("IMPORT_OF_E-MAIL_ADDRESSES"))?>',
											handler: email_import,
											icon: '<?=MEDIA?>icon/database_refresh.png'
										}, {
											xtype: 'tbseparator'
										}, {
											text: '<?=$this->db->escape_str($this->lang->line("SENDING"))?>',
											handler: send,
											icon: '<?=MEDIA?>icon/email_go.png'
										}, {
											xtype: 'tbseparator'
										},{
											text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
											handler: close,
											icon: '<?=MEDIA?>icon/cancel.png'
										}, {
											xtype: 'tbseparator'
										},{
											text: '<?=$this->db->escape_str($this->lang->line("RESET"))?>',
											handler: function() {
												newsletterForm.getForm().reset();
											}
										}],
										buttonAlign : 'right'
									}

							});
							winNewsletter.show(this);

						}
					}
				]
			},

			plugins:[
				new Ext.ux.grid.Search({
					minChars:2,
					iconCls: 'icon-zoom',
					searchText:'<?=$this->db->escape_str($this->lang->line("SEARCH"))?>',
					position:'top',
					minCharsTipText:'<?=$this->db->escape_str($this->lang->line("MINIMUM_TWO_CHARACTERS_IS_REQUIRED"))?>',
					selectAllText: '<?=$this->db->escape_str($this->lang->line("SELECT_ALL"))?>',
					width:200,
					disableIndexes:[],
					autoFocus:true
				})]

		});

		grid.render('grid-table-newsletter');

		grid.getSelectionModel().on('selectionchange', function(sm){
			grid.removeBtn.setDisabled(sm.getCount() < 1);
			grid.sendBtn.setDisabled(sm.getCount() < 1);
		});

		store.load();

		function save() {
			if(!newsletterForm.getForm().isValid()) {
				Ext.Msg.show({
					title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
					msg: '<?=$this->db->escape_str($this->lang->line("PLEASE_CORRECT_THE_ERRORS"))?>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			} else {
				if(newsletterForm.getForm().isDirty()) {
					newsletterForm.getForm().submit({
						url: '<?=site_url()?>admin/newsletter_insert_update',
						success: function(form, resp){
							if(resp.result.error) {
								Ext.Msg.show({
									title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
									msg: resp.result.error,
									buttons: Ext.Msg.OK,
									icon: Ext.MessageBox.ERROR
								});
							} else {
								winNewsletter.close();
							}
						}
					});
				} else {
					winNewsletter.close();
				}
			}
		};

		function close() {
			winNewsletter.close();
		};

		function removeNewsletter(btn) {
			if(btn == 'yes') {
				Ext.Ajax.request({url: '<?=site_url()?>admin/newsletter_insert_update', params: 'del=1&nltId=' + grid.getSelectionModel().getSelections()[0].data.nltId, success: function() {
					store.reload(store.lastOptions);
					}
				});
			}
		}

		function send() {
			if(newsletterForm.getForm().isDirty()) {
				newsletterForm.getForm().submit({
					url: '<?=site_url()?>admin/newsletter_send',
					success: function(form, resp){
						if(resp.result.error) {
							Ext.Msg.show({
								title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
								msg: resp.result.error,
								buttons: Ext.Msg.OK,
								icon: Ext.MessageBox.ERROR
							});
						} else if(resp.result.message) {
							Ext.Msg.show({
								title:'<?=$this->db->escape_str($this->lang->line("THE_FOLLOWING_EVENT_HAPPENED"))?>',
								msg: resp.result.message,
								buttons: Ext.Msg.OK,
								icon: Ext.MessageBox.INFO,
							});
							winNewsletter.close();
						} else {
							Ext.Msg.show({
								title:'<?=$this->db->escape_str($this->lang->line("MESSAGE_SENT"))?>',
								msg: '<?=$this->db->escape_str($this->lang->line("MESSAGE_IS_SUCCESSFULLY_SENT_TO_THE_GIVEN_ADDRESSES"))?>',
								buttons: Ext.Msg.OK,
								icon: Ext.MessageBox.INFO
							});
							winNewsletter.close();
						}
					}
				});
			} else {
				winNewsletter.close();
			}
		}

		function email_import() {
			Ext.Ajax.request({url: '<?=site_url()?>admin/newsletter_import', success: function(resp) {
				Ext.getCmp('frmNltAddressList').setValue(resp.responseText);
				}
			});
		}

	})
</script>


<div id="grid-table-newsletter"></div>